<template>
  <div class="detail">
    <div class="header">
      <div class="back-button" @click="goBack">
        <i class="fas fa-arrow-left"></i> 返回
      </div>
      <h1>{{ title }}</h1>
    </div>
    
    <div class="customer-table">
      <table>
        <thead>
          <tr>
            <th class="col-index">序号</th>
            <th class="col-nickname">客户昵称</th>
            <th class="col-profile">客户画像</th>
            <th class="col-needs">需求与痛点</th>
            <th class="col-tags">标签</th>
            <th class="col-quality">沟通质量</th>
            <th class="col-action">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="customer in customers" :key="customer.id">
            <td>{{ customer.index }}</td>
            <td>{{ customer.nickname }}</td>
            <td class="profile-cell">{{ customer.profile }}</td>
            <td class="needs-cell">
              <ul v-if="customer.needs && customer.needs.length > 0">
                <li v-for="(need, i) in customer.needs" :key="i">{{ need }}</li>
              </ul>
              <span v-else>暂无数据</span>
            </td>
            <td>
              <div class="tag-container">
                <span class="tag" v-for="(tag, i) in customer.tags" :key="i">{{ tag }}</span>
              </div>
            </td>
            <td class="communication-cell">
              <div v-if="customer.communication_quality">
                <div v-if="customer.communication_quality.strengths && customer.communication_quality.strengths.length > 0">
                  <div class="comm-section-title">优点:</div>
                  <ul class="comm-list">
                    <li v-for="(strength, i) in customer.communication_quality.strengths" :key="i">{{ strength }}</li>
                  </ul>
                </div>
                <div v-if="customer.communication_quality.improvements && customer.communication_quality.improvements.length > 0">
                  <div class="comm-section-title improvement-title">改进点:</div>
                  <ul class="comm-list improvement-list">
                    <li v-for="(improvement, i) in customer.communication_quality.improvements" :key="i">{{ improvement }}</li>
                  </ul>
                </div>
                <span v-if="!customer.communication_quality.strengths.length && !customer.communication_quality.improvements.length">暂无数据</span>
              </div>
              <span v-else>暂无数据</span>
            </td>
            <td>
              <button class="view-chat-btn" @click="showChatHistory(customer)">查看聊天记录</button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div v-if="customers.length === 0" class="no-data">
        暂无数据
      </div>
    </div>
    
    <!-- 聊天记录弹窗 -->
    <div class="modal" v-if="showModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ selectedCustomer.nickname }} 的聊天记录</h2>
          <span class="close-btn" @click="closeModal">&times;</span>
        </div>
        <div class="modal-body">
          <div class="chat-container">
            <div v-for="(message, index) in chatMessages" :key="index" class="chat-message" :class="getChatMessageClass(message)">
              <div class="message-sender">{{ getMessageSender(message) }}</div>
              <div class="message-content">{{ getMessageContent(message) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import api from '../services/api';

export default {
  props: {
    type: {
      type: String,
      required: true
    },
    value: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const router = useRouter();
    const customers = ref([]);
    const showModal = ref(false);
    const selectedCustomer = ref({});
    const chatMessages = ref([]);
    
    const title = computed(() => {
      if (props.type === 'sales_stage') {
        return `销售阶段: ${props.value}`;
      } else if (props.type === 'platform') {
        return `平台: ${props.value}`;
      } else if (props.type === 'sales_stages') {
        try {
          // 尝试解析销售阶段数组
          const stages = JSON.parse(decodeURIComponent(props.value));
          return `销售阶段: ${stages.join(', ')}`;
        } catch (e) {
          return '销售阶段: 多阶段';
        }
      } else if (props.type === 'search') {
        return `搜索结果: ${props.value}`;
      } else if (props.type === 'month') {
        return `新增沟通客户（${props.value}）`;
      }
      return '客户列表';
    });
    
    const fetchData = async () => {
      try {
        let response;
        if (props.type === 'sales_stage') {
          response = await api.getFilteredCustomers('sales_stage', props.value);
        } else if (props.type === 'platform') {
          response = await api.getFilteredCustomers('platform', props.value);
        } else if (props.type === 'sales_stages') {
          // 处理多个销售阶段的情况
          try {
            // 尝试解析销售阶段数组
            const stages = JSON.parse(decodeURIComponent(props.value));
            // 调用新的API接口获取多个销售阶段的客户
            response = await api.getFilteredCustomersByStages(stages);
          } catch (e) {
            console.error('解析销售阶段数组出错:', e);
          }
        } else if (props.type === 'search') {
          // 处理搜索的情况
          response = await api.searchCustomers(props.value);
        } else if (props.type === 'month') {
          // 新增：按月获取客户详情
          response = await api.getCustomersByMonth(props.value);
        }
        if (response && response.data) {
          customers.value = response.data;
        }
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    
    const goBack = () => {
      router.push('/');
    };
    
    const showChatHistory = (customer) => {
      selectedCustomer.value = customer;
      chatMessages.value = customer.chat_history || [];
      showModal.value = true;
    };
    
    const closeModal = () => {
      showModal.value = false;
    };
    
    const getMessageSender = (message) => {
      // 获取消息发送者（第一个键）
      return Object.keys(message)[0];
    };
    
    const getMessageContent = (message) => {
      // 获取消息内容（第一个值）
      const key = Object.keys(message)[0];
      return message[key];
    };
    
    const getChatMessageClass = (message) => {
      const sender = getMessageSender(message);
      return sender === '我' ? 'self-message' : 'other-message';
    };
    
    onMounted(() => {
      fetchData();
    });
    
    return {
      customers,
      title,
      goBack,
      showModal,
      selectedCustomer,
      chatMessages,
      showChatHistory,
      closeModal,
      getMessageSender,
      getMessageContent,
      getChatMessageClass
    };
  }
};
</script>

<style scoped>
.detail {
  background-color: #1E1E2E;
  color: #fff;
  min-height: 100vh;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.back-button {
  background-color: #4B7BEC;
  color: #fff;
  padding: 8px 15px;
  border-radius: 5px;
  cursor: pointer;
  margin-right: 20px;
}

.customer-table {
  background-color: #282A42;
  border-radius: 10px;
  padding: 15px;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

th, td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #3C3F58;
  vertical-align: top;
  overflow-wrap: anywhere;
  word-break: break-word;
  white-space: normal;
}

/* 设置列宽度 */
.col-index {
  width: 5%;
}

.col-nickname {
  width: 15%;
}

.col-profile {
  width: 20%;
}

.col-needs {
  width: 15%;
}

.col-tags {
  width: 12%;
}

.col-quality {
  width: 30%;
  min-width: 280px;
}

.col-action {
  width: 10%;
}

th {
  background-color: #3C3F58;
  color: #fff;
}

tr:hover {
  background-color: #32344A;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #8C9EFF;
}

.profile-cell {
  max-width: 250px;
  word-break: break-word;
  white-space: normal;
  letter-spacing: normal;
}

.needs-cell {
  max-width: 180px;
  word-break: break-word;
  white-space: normal;
  letter-spacing: normal;
}

.time-cell {
  font-size: 12px;
  word-break: break-word;
  white-space: normal;
}

.time-range {
  margin-bottom: 8px;
  padding: 5px;
  background-color: rgba(60, 63, 88, 0.5);
  border-radius: 4px;
}

.time-label {
  font-weight: bold;
  color: #8C9EFF;
}

.communication-cell {
  max-width: 350px;
  min-width: 280px;
  font-size: 13px;
  word-break: break-word;
  white-space: normal;
  letter-spacing: normal;
}

.comm-section-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #8C9EFF;
  font-size: 12px;
}

.improvement-title {
  color: #FF8C9E;
  margin-top: 10px;
  font-size: 12px;
}

.comm-list {
  margin: 0;
  padding-left: 20px;
  font-size: 12px;
  white-space: normal;
  word-break: break-word;
  letter-spacing: normal;
  line-height: 1.4;
}

.improvement-list li {
  color: #FF8C9E;
  white-space: normal;
  word-break: break-word;
  letter-spacing: normal;
  line-height: 1.4;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.tag {
  background-color: #4B7BEC;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
}

.view-chat-btn {
  background-color: #7A88FF;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.view-chat-btn:hover {
  background-color: #5A68DF;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #282A42;
  border-radius: 10px;
  width: 80%;
  max-width: 800px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #3C3F58;
}

.close-btn {
  font-size: 24px;
  cursor: pointer;
  color: #8C9EFF;
}

.close-btn:hover {
  color: #fff;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex-grow: 1;
}

.chat-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.chat-message {
  padding: 10px 15px;
  border-radius: 8px;
  max-width: 80%;
}

.self-message {
  background-color: #4B7BEC;
  align-self: flex-end;
}

.other-message {
  background-color: #3C3F58;
  align-self: flex-start;
}

.message-sender {
  font-weight: bold;
  margin-bottom: 5px;
}

.message-content {
  word-break: break-word;
}

ul {
  margin: 0;
  padding-left: 20px;
}
</style> 